package rsj.service;

import com.rlyy.aibase.utils.base.MapNode;
import com.rlyy.aibase.utils.base.Node;
import com.rlyy.aibase.utils.base.TableNode;
import common.util.Assert;
import common.util.CommonUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import rsj.dao.ProductDao;
import rsj.dao.PrtyDao;
import rsj.domain.ProductPageQuery;
import rsj.manager.ProdManager;
import rsj.sql.account.AccountProductDao;
import rsj.sql.product.ProductInfoDao;
import rsj.table.SYS_PROD;
import rsj.util.PaginationData;

import java.util.HashMap;
import java.util.Map;

@Component
public class ProductService {

    @Autowired
    private ProductInfoDao productInfoDao;

    @Autowired
    private AccountProductDao accountProductDao;

    private static final Logger logger = LoggerFactory.getLogger(ProductService.class);

    private static final ProductDao productDao = ProductDao.getInstance();
    private static final ProdManager prodManager = ProdManager.getInstance();
    private static final PrtyDao prtyDao = PrtyDao.getInstance();

    public String insertOrUpdate(final MapNode data) {
        checkParameter(data);
        if (StringUtils.isBlank(data.getValue(SYS_PROD.Prod_Seq))) {
            String seq = productDao.getMaxSeq();
            data.putNode(SYS_PROD.Prod_Seq, String.valueOf(CommonUtil.safeInt(seq) + 100));
        }
        return prodManager.insertOrUpdate(data);
    }

    private void checkParameter(MapNode data) {
        /**
         * 1.新增时SEQ由后台声场
         * 2.编辑时SEQ由前台录入
         */
        if (StringUtils.isNotBlank(data.getValue(SYS_PROD.Prod_Seq))) {
            int Prod_Seq = data.getValueIntDef(SYS_PROD.Prod_Seq, -1);
            Assert.isTrue(Prod_Seq > 0, "排序参数，Prod_Seq大于0");
        }

        String Prod_Type_Fid = data.getValueDef(SYS_PROD.Prod_Type_Fid, "");
        String Prod_Type_Sid = data.getValueDef(SYS_PROD.Prod_Type_Sid, "");

        // 产品二级分类必须在一级分类下
        MapNode mapNode = prtyDao.getBySid(Prod_Type_Sid);
        Assert.isTrue(Prod_Type_Fid.equalsIgnoreCase(mapNode.getValue("Prty_Fid")), "产品一级类别必须和二级类别对应");

        Assert.isNotBlank(Prod_Type_Fid, "产品大类型参数必填");
        Assert.isNotBlank(Prod_Type_Sid, "产品二级类型参数必填");

        String Prod_Status = data.getValueDef(SYS_PROD.Prod_Status, "");
        Assert.isTrue("0".equals(Prod_Status) | "1".equals(Prod_Status), "产品状态只能是（0可用，1停用）");
        String Prod_Hpage = data.getValueDef(SYS_PROD.Prod_Hpage, "");
        Assert.isTrue("0".equals(Prod_Hpage) | "1".equals(Prod_Hpage), "是否首页只能是（0可用，1停用）");
        String Prod_Name = data.getValueDef(SYS_PROD.Prod_Name, "");
        Assert.isNotBlank(Prod_Name, "产品名称必填");
        String Prod_Uid = data.getValueDef(SYS_PROD.Prod_Uid, "");
        Assert.isNotBlank(Prod_Uid, "Prod_Uid不能为空！");
        String Prod_Icon = data.getValueDef(SYS_PROD.Prod_Icon, "");
        Assert.isNotBlank(Prod_Icon, "Prod_Icon必填且非空！");
        String Prod_Overview = data.getValueDef(SYS_PROD.Prod_Overview, "");
        Assert.isNotBlank(Prod_Overview, "Prod_Overview必填且非空！");
        String Prod_Addr = data.getValueDef(SYS_PROD.Prod_Addr, "");
        Assert.isNotBlank(Prod_Addr, "Prod_Addr必填且非空！");
        String Prod_Callmethod = data.getValueDef(SYS_PROD.Prod_Callmethod, "");
        Assert.isNotBlank(Prod_Callmethod, "Prod_Callmethod必填且非空！");
        String Prod_Encoding = data.getValueDef(SYS_PROD.Prod_Encoding, "");
        Assert.isNotBlank(Prod_Encoding, "Prod_Encoding必填且非空！");
        String Prod_Datasig = data.getValueDef(SYS_PROD.Prod_Datasig, "");
        Assert.isNotBlank(Prod_Datasig, "Prod_Datasig必填且非空！");
        String Prod_Response = data.getValueDef(SYS_PROD.Prod_Response, "");
        Assert.isNotBlank(Prod_Response, "Prod_Response必填且非空！");
        String Prod_Quest = data.getValueDef(SYS_PROD.Prod_Quest, "");
        Assert.isNotBlank(Prod_Quest, "Prod_Quest必填且非空！");
        String Prod_Paramin = data.getValueDef(SYS_PROD.Prod_Paramin, "");
        Assert.isNotBlank(Prod_Paramin, "Prod_Paramin必填且非空！");
        String Prod_Paramout = data.getValueDef(SYS_PROD.Prod_Paramout, "");
        Assert.isNotBlank(Prod_Paramout, "Prod_Paramout必填且非空！");
        String Prod_Rexamle = data.getValueDef(SYS_PROD.Prod_Rexamle, "");
        Assert.isNotBlank(Prod_Rexamle, "Prod_Rexamle必填且非空！");
        String Prod_Price = data.getValueDef(SYS_PROD.Prod_Price, "");
        Assert.isNotBlank(Prod_Price, "Prod_Price必填且非空！");
        String Prod_Description = data.getValueDef(SYS_PROD.Prod_Description, "");
        Assert.isNotBlank(Prod_Description, "Prod_Description必填且非空！");
        String Prod_Ctime = data.getValueDef(SYS_PROD.Prod_Ctime, "");
        Assert.isNotBlank(Prod_Ctime, "Prod_Ctime必填且非空！");
        String Prod_Endtime = data.getValueDef(SYS_PROD.Prod_Endtime, "");
        Assert.isNotBlank(Prod_Endtime, "Prod_Endtime必填且非空！");
        String Prod_Docname = data.getValueDef(SYS_PROD.Prod_Docname, "");
        Assert.isNotBlank(Prod_Docname, "Prod_Docname必填且非空！");
        String Prod_Docid = data.getValueDef(SYS_PROD.Prod_Docid, "");
        Assert.isNotBlank(Prod_Docid, "Prod_Docid必填且非空！");
    }

    public MapNode getProductInfoById(String prodId, String orgId) {
        MapNode prod = productDao.getById(prodId, orgId);
        if(StringUtils.isBlank(prod.getValue("Sta_Status"))) {
            //计算申请中的合同
            Node prodOrgpStatus = productInfoDao.applyingProductByOrgId(orgId, prod.getValue("Prod_Id"));
            prod.putNode("Sta_Status", prodOrgpStatus.value());
        }
        MapNode product = accountProductDao.getAccountProduct(orgId, prod.getValue("Prod_Uid"));
        prod.putNode("Purchase_Status", StringUtils.isNotBlank(product.getValue("Charge_Price")) ? product.getValue("Charge_Price") : "详谈");
        return prod;
    }

    public TableNode getHomePageData(String orgId) {
        TableNode homePageData = productDao.getHomePageData(orgId);
        for (int i = 0; i< homePageData.length(); i++){
            MapNode prod = homePageData.getMapNode(i);
            if(StringUtils.isBlank(prod.getValue("Sta_Status")) && StringUtils.isNotBlank(orgId)) {
                //计算申请中的合同
                Node prodOrgpStatus = productInfoDao.applyingProductByOrgId(orgId, prod.getValue("Prod_Id"));
                prod.putNode("Sta_Status", prodOrgpStatus.value());
            }
        }
        return homePageData;
    }

    public TableNode getProdClass() {
        return productDao.getProdClass();
    }

    public PaginationData<TableNode> getPageByQuery(ProductPageQuery query) {
        return productDao.getPageByQuery(query);
    }

    public PaginationData<TableNode> getDataMarketPage(ProductPageQuery query) {
        PaginationData<TableNode> paginationData = new PaginationData<>();
        Node node = productInfoDao.countProduct(query);
        TableNode tableNode = productInfoDao.dataMarketProductListPage(query);
        paginationData.setDataList(tableNode);
        paginationData.setTotalCount(node.valueInt());
        return paginationData;
    }


    public PaginationData<TableNode> getPage(ProductPageQuery query) {
        PaginationData<TableNode> paginationData = new PaginationData<>();
        Node node = productInfoDao.countProduct(query);
        TableNode tableNode = productInfoDao.productListPage(query);
        paginationData.setDataList(tableNode);
        paginationData.setTotalCount(node.valueInt());
        return paginationData;
        //return productDao.getPage(query);
    }

    public PaginationData<TableNode> getPageByOrgid(ProductPageQuery query) {
        PaginationData<TableNode> pageByOrgId = productDao.getPageByOrgId(query);
        TableNode accountProducts = accountProductDao.getAccountProducts(query.getOrgId());
        Map<String,String> prodPrice = new HashMap<>();
        for (int i = 0; i< accountProducts.length(); i++){
            MapNode prod = accountProducts.getMapNode(i);
            prodPrice.put(prod.getValue("Prod_Uid"), StringUtils.isNotBlank(prod.getValue("Charge_Price")) ? prod.getValue("Charge_Price") : "详谈");
        }
        TableNode dataList = pageByOrgId.getDataList();
        for (int i = 0; i< dataList.length(); i++){
            MapNode prod = dataList.getMapNode(i);
            prod.putNode("Prod_Price",prodPrice.getOrDefault(prod.getValue("Prod_Uid"),"详谈"));
            if(StringUtils.isBlank(prod.getValue("Sta_Status"))) {
                Node prodOrgpStatus = productInfoDao.applyingProductByOrgId(query.getOrgId(), prod.getValue("Prod_Id"));
                prod.putNode("Sta_Status", prodOrgpStatus.value());
            }
        }
        return pageByOrgId;
    }

    public int sectionUpdateProd(MapNode data) {
        return productDao.sectionUpdateProd(data);
    }


    /**
     * 产品列表分页
     *
     * @param query 查询
     * @return {@link String}
     */
    public String productListSql(ProductPageQuery query) {
        String sql = "SELECT  prod.prod_id, prod.prod_name, prty.prty_sid, prty.prty_sname, prty.prty_fid" +
                " , prty.prty_fname, prod.prod_status,prod.prod_sales, prod.prod_seq, prod.prod_overview, prod.prod_price " +
                ", to_char(prod.prod_utime,'yyyy-MM-dd') prod_utime, prod_ctime, prod_endtime, prod.prod_uid FROM sys.sys_prod AS prod "
                + " LEFT JOIN sys.sys_prty prty ON prod.prod_type_sid = prty.prty_sid WHERE 1 = 1 ";
        if(StringUtils.isNotBlank(query.getProdStatus())){
            sql += " AND prod.prod_status = #{prodStatus}";
        }
        if (StringUtils.isNotBlank(query.getProdName())) {
            sql += " AND prod.prod_name LIKE #{%prodName%}";
        }
        if (StringUtils.isNotBlank(query.getProdType())) {
            sql += " AND prty.prty_fid = #{prodType}";
        }
        sql += " ORDER BY prod.prod_uid LIMIT #{pageSize} OFFSET #{pageCount}";
        return sql;
    }


    /**
     * 数据市场产品列表分页
     *
     * @param query 查询
     * @return {@link String}
     */
    public String dataMarketProductListSql(ProductPageQuery query) {
        String sql = "SELECT  prod.prod_id, prod.prod_name, prty.prty_sid, prty.prty_sname, prty.prty_fid" +
                " , prty.prty_fname, prod.prod_status,prod.prod_sales, prod.prod_seq, prod.prod_overview, prod.prod_price " +
                ", to_char(prod.prod_utime,'yyyy-MM-dd') prod_utime, prod_ctime, prod_endtime, prod.prod_uid FROM sys.sys_prod AS prod "
                + " LEFT JOIN sys.sys_prty prty ON prod.prod_type_sid = prty.prty_sid WHERE 1 = 1 ";
        if(StringUtils.isNotBlank(query.getProdStatus())){
            sql += " AND prod.prod_status = #{prodStatus}";
        }
        if (StringUtils.isNotBlank(query.getProdName())) {
            sql += " AND prod.prod_name LIKE #{%prodName%}";
        }
        if (StringUtils.isNotBlank(query.getProdType())) {
            sql += " AND prty.prty_fid = #{prodType}";
        }
        sql += " ORDER BY prod.prod_seq::int DESC LIMIT #{pageSize} OFFSET #{pageCount}";
        return sql;
    }


    /**
     * 统计产品的sql
     *
     * @param query 查询
     * @return {@link String}
     */
    public String countProductSql(ProductPageQuery query) {
        String countSql = "SELECT  COUNT(*)  FROM sys.sys_prod prod";
        String condition = "";
        if (StringUtils.isNotBlank(query.getProdType())) {
            countSql += " LEFT JOIN sys.sys_prty prty ON prod.prod_type_sid = prty.prty_sid";
            condition += " AND prty.prty_fid = #{prodType}";
        }
        if (StringUtils.isNotBlank(query.getProdName())) {
            condition += " AND prod.prod_name LIKE #{%prodName%}";
        }
        if(StringUtils.isNotBlank(query.getProdStatus())){
            condition += " AND prod.prod_status = #{prodStatus}";
        }
        countSql += " WHERE 1 = 1 " + condition;
        return countSql;
    }


}
